import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { ActionReducerMapBuilder, AsyncThunk, PayloadAction, Slice } from '@reduxjs/toolkit'
import { getGearList, GetGearListParams } from './withdrawGearAPI'
import { DataType } from '@/pages/WithdrawGear/Table'
import { v4 } from 'uuid'

interface InitialState {
  params: GetGearListParams,
  table: {
    status: 'init' | 'loading' | 'success' | 'error',
    data?: Res,
    params?:GetGearListParams
  },
  create: {
    type: 'create' | 'update',
    open: boolean,
    record?: DataType
  }
}

const initialState:InitialState = {
  params: {
    channel: '',
    country: '',
    wd_way: '',
    page: 1,
    page_size: 10
  },
  table: {
    status: 'init'
  },
  create: {
    type: 'create',
    open: false
  }
}

type Res = {
  data: {
    page: number,
    total: number,
    page_data: DataType[]
  }
}
type AsyncRes = {
  res: Res,
  params: GetGearListParams
}
export const getGearListAsync:AsyncThunk<AsyncRes, GetGearListParams, {}> = createAsyncThunk<AsyncRes, GetGearListParams, {}>('withdrawGear/getGearListAsync', async params => {
  const res:Res = await getGearList(params)
  return {
    res, params
  }
})
const tableStatus = (builder: ActionReducerMapBuilder<InitialState>) => {
  builder.addCase(getGearListAsync.pending, state => {
    state.table.status = 'loading'
  }).addCase(getGearListAsync.fulfilled, (state, action) => {
    state.table.status = 'success'
    if(Array.isArray(action?.payload?.res?.data?.page_data)){
      action.payload.res.data.page_data.forEach(i => i.uuid = v4())
    }
    state.table.data = action.payload.res
    state.table.params = action.payload.params
  }).addCase(getGearListAsync.rejected, state => {
    state.table.status = 'error'
  })
}

type Reducers = {
  changeParams: (state: InitialState, action:PayloadAction<Partial<GetGearListParams>>) => void,
  changeCreate: (state: InitialState, action: PayloadAction<Partial<InitialState['create']>>) => void
}
type Selectors = {}
const withdrawGearSlice:Slice<InitialState, Reducers, 'withdrawGear', 'withdrawGear', Selectors> = createSlice<InitialState, Reducers, 'withdrawGear', Selectors, 'withdrawGear'>({
  name: 'withdrawGear',
  initialState,
  reducers:{
    changeParams(state, action){
      state.params = {
        ...state.params,
        ...action.payload
      }
    },
    changeCreate(state, action){
      state.create = {
        ...state.create,
        ...action.payload
      }
    }
  },
  extraReducers(builder) {
    tableStatus(builder)
  },
})

export const { changeParams, changeCreate } = withdrawGearSlice.actions

export default withdrawGearSlice.reducer